/**
 * FormFieldMarkdown
 */
layui.define(['FormField', 'yunj', 'jquery'], function (exports) {

    let FormField = layui.FormField;
    let win = window;
    let doc = document;
    let $ = layui.jquery;

    class FormFieldMarkdown extends FormField {

        constructor(options = {}) {
            super(options);
            this.mode = null;           // 模式
            this.markdown_id = null;    // 容器id
            this.markdown = null;       // 对象
        }

        defineExtraArgs() {
            let that = this;
            return {
                mode: "editormd",
                modeConfig: {
                    editormd: {
                        height: 250,
                        watch: false,
                        placeholder: "此处开始编写...",
                        imageFormats: yunj.config("file.upload_img_ext").split(","),
                        // 全屏展开编辑有bug
                        toolbar: [
                            "undo", "redo", "|", "bold", "del", "italic", "quote", "|"
                            , "h1", "h2", "h3", "h4", "|", "list-ul", "list-ol", "hr", "|"
                            , "align-left", "align-center", "align-right", "align-justify", "|"
                            , "table", "datetime", "html-entities", "pagebreak", "code", "code-block", "|"
                            , "link", "reference-link", "image", "video", "|"
                            , "watch", "preview", /*"fullscreen",*/ "clear", "search", "|", "help"
                        ]
                    }
                },
                readonly: false
            };
        }

        handleArgs(args) {
            let that = this;
            let mode = args.mode;
            let modeConfig = args.modeConfig;
            let defaultModeConfig = that.defineExtraArgs().modeConfig;
            if (!modeConfig.hasOwnProperty(mode)) {
                modeConfig[mode] = defaultModeConfig[mode];
                args.modeConfig = modeConfig;
                return args;
            }
            modeConfig[mode] = Object.assign({}, defaultModeConfig[mode], modeConfig[mode]);
            if (mode === "editormd") {
                // 若果是editormd，对toolbar取交集
                modeConfig[mode].toolbar = yunj.arrayIntersect(modeConfig[mode].toolbar, defaultModeConfig[mode].toolbar);
            }
            args.modeConfig = modeConfig;
            return args;
        }

        defineBoxHtml() {
            let that = this;
            return `<div class="layui-form-item yunj-form-item yunj-form-markdown" id="${that.id}">__layout__</div>`;
        }

        layoutControl() {
            let that = this;
            return that[`layout_control_${that.mode}`]();
        }

        async renderBefore() {
            let that = this;
            that.mode = that.args.mode;
            that.markdown_id = `${that.id}_markdown_${that.mode}`;
            await that[`render_before_${that.mode}`]();
            return 'done';
        }

        async renderDone() {
            let that = this;
            await that[`render_done_${that.mode}`]();
            return 'done';
        }

        setValue(val = '') {
            let that = this;
            that[`set_value_${that.mode}`](val);
        }

        getValue() {
            let that = this;
            return that[`get_value_${that.mode}`]();
        }

        layout_control_editormd() {
            let that = this;
            return `<div class="layui-input-inline yunj-form-item-control"><div id="${that.markdown_id}" style="width: auto;"><textarea></textarea></div></div>`;
        }

        async render_before_editormd() {
            let that = this;
            win.jQuery = $;
            win.$ = $;
            await yunj.includeCss('/static/yunj/libs/editor.md/css/editormd.min.css');
            await yunj.includeJs('/static/yunj/libs/editor.md/editormd.min.js');
            return 'done';
        }

        async render_done_editormd() {
            let that = this;
            await new Promise(resolve => {
                let options = that.def_options_editormd();
                options.onload = () => resolve('done');
                that.markdown = editormd(that.markdown_id, options);
            });
            return 'done';
        }

        set_value_editormd(val = '') {
            let that = this;
            that.markdown.setMarkdown(val);
        }

        get_value_editormd() {
            let that = this;
            return that.markdown.getMarkdown();
        }

        // 默认配置
        def_options_editormd() {
            let that = this;
            return {
                width: "auto",
                height: that.args.modeConfig.editormd.height,
                path: '/static/yunj/libs/editor.md/lib/',
                watch: that.args.modeConfig.editormd.watch,
                placeholder: that.args.modeConfig.editormd.placeholder,
                autoFocus: false,
                readOnly: that.args.readonly,
                taskList: true,
                tex: true,
                flowChart: true,
                sequenceDiagram: true,
                syncScrolling: "single",
                htmlDecode: "style,script,iframe|filterXSS",
                imageUpload: true,
                imageFormats: that.args.modeConfig.editormd.imageFormats,
                imageUploadURL: yunj.fileUploadUrl("editormd"),
                toolbarIcons: () => {
                    return that.args.modeConfig.editormd.toolbar;
                },
                toolbarIconsClass: {
                    "align-left": "fa-align-left",
                    "align-center": "fa-align-center",
                    "align-right": "fa-align-right",
                    "align-justify": "fa-align-justify",
                    "video": "fa-file-video-o",
                },
                lang: {
                    toolbar: {
                        "align-left": "左对齐",
                        "align-center": "居中对齐",
                        "align-right": "右对齐",
                        "align-justify": "两端对齐",
                        "video": "插入视频",
                    }
                },
                toolbarHandlers: {
                    "align-left": (cm, icon, cursor, selection) => {
                        cm.replaceSelection(`<p align="left">${selection}</p>`);
                        selection === "" && cm.setCursor(cursor.line, cursor.ch + 1);
                    },
                    "align-center": (cm, icon, cursor, selection) => {
                        cm.replaceSelection(`<p align="center">${selection}</p>`);
                        selection === "" && cm.setCursor(cursor.line, cursor.ch + 1);
                    },
                    "align-right": (cm, icon, cursor, selection) => {
                        cm.replaceSelection(`<p align="right">${selection}</p>`);
                        selection === "" && cm.setCursor(cursor.line, cursor.ch + 1);
                    },
                    "align-justify": (cm, icon, cursor, selection) => {
                        cm.replaceSelection(`<p align="justify">${selection}</p>`);
                        selection === "" && cm.setCursor(cursor.line, cursor.ch + 1);
                    },
                    "video": (cm, icon, cursor, selection) => {
                        cm.replaceSelection(`\r\n<video src="http://xxxx.com/xxxx.mp4" style="width: 100%; height: 100%;" controls="controls"></video>\r\n`);
                        selection === "" && cm.setCursor(cursor.line, cursor.ch + 1);
                    },
                },
            };
        }

        // 重载editormd，适配表单多tab模式下editormd被影响后不能正常显示
        reloadEditormd() {
            let that = this;
            let options = that.def_options_editormd();
            options.markdown = that.getValue();
            that.markdown = editormd(that.markdown_id, options);
        }

        defineExtraEventBind() {
            let that = this;

        }

    }

    exports('FormFieldMarkdown', FormFieldMarkdown);
});